import React from 'react'
import PropTypes from 'prop-types'
import { withRouter, matchPath } from 'react-router'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { Layout, Menu, Icon } from 'antd'
import { Link } from 'react-router-dom'
import { updateNavPath } from '../../actions/menu'
import {jsonToTreeJson,findMenuByUrl} from "../../utils";

const SubMenu = Menu.SubMenu

import './index.less'

const defaultProps = {
  items: []
}

const propTypes = {
  items: PropTypes.array
}

const { Sider } = Layout;

const isActive = (path, history) => {
  return matchPath(path, {
    path: history.location.pathname,
    exact: true,
    strict: false
  })
}

class Sidebar extends React.Component {

  state = {
    openKey: "sub1",
    activeKey: "menu101",
    collapsed: false,
    mode: 'inline',
  }

  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
      mode: !this.state.collapsed ? 'vertical' : 'inline',
    });
  }

  componentWillMount () {
    
  }

  componentWillReceiveProps(nextProps) {
    let _items = jsonToTreeJson(nextProps.items,'1');
    let openKeys = [];
    Array.isArray(_items) && _items.map((item, i) => {
      Array.isArray(item.child) && item.child.map((node) => {
        openKeys.push('sub1_menu' + node.key);
      })
    });
    this.setState({
      openKeys:openKeys
    });
  }

  menuClickHandle = (item) => {
    const { navpath,items,main_menu_index,location } = this.props;
    
    this.setState({
      activeKey: item.key
    })
    
    // 如果没有选取任何一级菜单的值就通过
    if(main_menu_index){
      // 如果还没有选择任何的主菜单默认计算为选择了主菜单的第一个选项
      if(navpath.length<=0){
        item.keyPath.push('bar_menu' + items[0].key);
      } else {
        item.keyPath.push('bar_menu' + navpath[0].key);
      }
      this.props.updateNavPath(item.keyPath, item.key,main_menu_index);
    }
    else{
      let pathname = location.pathname;
      let selectMenu = findMenuByUrl(items,pathname);
      const treeMenus = jsonToTreeJson(items,'1');
      item.keyPath.push('bar_menu'+selectMenu.parent.parent.id);
      this.props.updateNavPath(item.keyPath, item.key);
    }
  }

  render () {
    const { items, updateNavPath, history ,current,main_menu_index,location } = this.props;
    let { activeKey,openKeys } = this.state;
    let pathname = location.pathname;
    let selectMenu = findMenuByUrl(items,pathname);

    // 菜单单位解析器
    const _menuProcess = (nodes, pkey) => {
      return Array.isArray(nodes) && nodes.map((item, i) => {
        const menu = _menuProcess(item.child, item.key);
        if(item.url && isActive(item.url, history)){
          activeKey = 'sub2_menu'+item.key
        }

        // 如果有孩子就采用有子菜单的结构
        if (menu.length > 0) {
          return (
            <SubMenu
              key={'sub1_menu'+item.key}
              title={<span><Icon type={item.icon} /><span className="nav-text">{item.name}</span></span>}
            >
              {menu}
            </SubMenu>
          )
        } 
        // 没有孩子就采用没有子菜单的结构
        else {
          return (
            <Menu.Item key={'sub2_menu'+item.key}>
              {
                item.url ? <Link to={item.url}>{item.icon && <Icon type={item.icon} />}{item.name}</Link> : <span>{item.icon && <Icon type={item.icon} />}{item.name}</span>
              }
            </Menu.Item>
          )
        }
      });
    }

    const _items = jsonToTreeJson(items,'1');
    let _currentItem = null;
    if(selectMenu){
      for(var i=0;i<_items.length;i++){
        if(_items[i].id == selectMenu.parent.parent.id){
          _currentItem = _items[i];
        }
      }
    }
    
    if(_items.length<=0){
      return (<Sider
        trigger={null}
        collapsible
        collapsed={this.state.collapsed}
        onCollapse={this.onCollapse}
      >
      </Sider>);
    }else{
      let children;
      if(typeof(main_menu_index) != 'undefined'){
        children = _items[main_menu_index].child;
      } else {
        children = _currentItem?_currentItem.child:_items[0].child;
      }
      
      const menu = _menuProcess(children);
      if(typeof(openKeys) == 'undefined'){
        openKeys = [];
        Array.isArray(items) && items.map((item, i) => {
          Array.isArray(item.child) && item.child.map((node) => {
            openKeys.push('sub1_menu' + node.key);
          })
        });
      }
      return (
        <Sider
            trigger={null}
            collapsible
            collapsed={this.state.collapsed}
            onCollapse={this.onCollapse}
            className={this.state.mode=='vertical'?'close':'open'}
          >
          <Menu
            mode={this.state.mode}
            selectedKeys={[activeKey]}
            defaultOpenKeys={[...openKeys]}
            onClick={this.menuClickHandle}
            style={{borderWidth:0}}
            inlineCollapsed = {true}
          >
            {menu}
          </Menu>
          <div className="sider-trigger">
            <Icon
                className="trigger"
                type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'}
                onClick={this.toggle}
              />
          </div>
        </Sider>
      )
    }
  }
}

Sidebar.propTypes = propTypes;
Sidebar.defaultProps = defaultProps;

function mapStateToProps(state) {
  return {
    items: state.menu.items,
    main_menu_index: state.menu.main_menu_index,
    navpath: state.menu.navpath
  }
}

function mapDispatchToProps(dispatch) {
  return {
    updateNavPath: bindActionCreators(updateNavPath, dispatch)
  }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Sidebar))
